package com.ww.springboot.boot.java8.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 *
 * allOf  anyOf
 *
 * 方法带不带async的区别是 后面执行的任务由哪个线程执行
 * 不带async 则指定最后完成任务的线程执行
 *   带async 则任意选择一个空闲线程执行
 * 两者的区别意义不大？？？
 *
 * @author 🧑 ‍wanwei
 * @since 2022-01-20 15:21
 */
public class CompletableFutureDemo6 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> a = CompletableFuture.runAsync(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("a"+Thread.currentThread());
            System.out.println("我执行完了");
        });
        CompletableFuture<Void> b = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("b"+Thread.currentThread());
            System.out.println("我也执行完了");
        });

//        CompletableFuture.allOf(a, b).whenCompleteAsync((m,k)->{
//            System.out.println("all2"+Thread.currentThread());
//            System.out.println("all finish 2");
//        }).get();

        CompletableFuture.allOf(a, b).whenComplete((m,k)->{
            System.out.println("all1"+Thread.currentThread());
            System.out.println("all finish");
        }).get();






        CompletableFuture<Void> c = CompletableFuture.runAsync(()->{
            System.out.println("我执行完了");
        });
        CompletableFuture<Void> d = CompletableFuture.runAsync(() -> {
            throw new RuntimeException("测试any");
            //System.out.println("我也执行完了");
        });
        CompletableFuture.anyOf(c, d).whenComplete((m,k)->{
            System.out.println("any finish");
        }).get();
    }
}
